from flask import render_template, request, send_file, Blueprint, redirect, url_for
from flask import current_app as app
import os
from rmblank import do_rmbalnk
from utils import get_file_info, get_timestamp, get_file_paths
import PyPDF3

bp = Blueprint('rmblank_routes', __name__, template_folder="templates")


@bp.route("/rmpdfblank")
def rmpdfblank():
    data = {}
    return render_template("rmblank/rmblank_upload.html", title="rmblank_upload", data=data)


@bp.route("/rmblankupload", methods=["POST"])
def upload_file():
    if request.method == "POST":
        if 'file' not in request.files:
            return 'No file part'

        file = request.files['file']
        if file.filename == '':
            return 'No selected file'

        filename = file.filename
        # 获取文件类型
        file_info = get_file_info(filename)
        if file_info[1] != "pdf":
            return 'File is not pdf'

        if file:
            ts = get_timestamp()
            file_name_ts = file_info[0] + "_" + ts  # 2021200151_1712548660
            new_filename = file_name_ts + "." + file_info[1]  # 2021200151_1712548660.pdf

            # base_path = /static/rmblank/2021200151_1712548660
            base_path = os.path.join(app.config['RM_BLANK_UPLOAD_FOLDER'], file_name_ts)
            if not os.path.exists(base_path):
                os.makedirs(base_path)
            file.save(os.path.join(base_path, new_filename))

            # 转存图片
            img_path = do_rmbalnk(base_path, new_filename)  # /static/rmblank/2021200151_1712548660/img
            print(img_path)

            return redirect(url_for("rmblank_routes.rmblank_show", folder_name=img_path))


@bp.route("/rmblank_show/<path:folder_name>")
def rmblank_show(folder_name):
    print("folder_name:", folder_name)
    file_paths = get_file_paths(folder_name)
    print("file_paths:", file_paths)
    data = {
        "img_path": folder_name.replace("\\", "/"),
        "file_paths": file_paths,
    }
    return render_template("rmblank/rmblank_show.html", title="rmblank", data=data)


"""
static/rmblank/
    example_123452345675869/
        example_123452345675869.pdf
        img/
            1.jpg
            2.jpg
            ...
        ==>example_123452345675869_noblank.pdf
"""


@bp.route("/rmblank", methods=["POST"])
def rmblank():
    selected_images = [int(_) for _ in request.form.getlist('selectedImages[]')]
    img_path = request.form["img_path"]  # /static/rmblank/2021200151_1712548660/img
    print("img_path:", img_path)
    base_path = img_path.split("/img")[0]
    pdf_name = img_path.split("/img")[0].split("/")[-1] + ".pdf"
    pdf_path = base_path + "/" + pdf_name
    print("pdf_path:", pdf_path)
    print("selected_images:", selected_images)
    print("base_path:", base_path)
    newpdf_path = remove_pages(pdf_path, selected_images, base_path)

    return redirect(url_for("rmblank_routes.do_rmblank", newpdf_path=newpdf_path))


@bp.route("/do_rmblank/<path:newpdf_path>", methods=["GET"])
def do_rmblank(newpdf_path):
    print("do_rmblank, newpdf_path:", newpdf_path)
    return send_file(newpdf_path, as_attachment=True)


def remove_pages(pdf_file, pages_to_remove, base_path):
    output = base_path + "/output.pdf"
    # 打开PDF文件
    with open(pdf_file, 'rb') as f:
        reader = PyPDF3.PdfFileReader(f)
        writer = PyPDF3.PdfFileWriter()

        # 遍历每一页
        for page_num in range(reader.numPages):
            # 如果该页不在要删除的页列表中，则将其添加到输出PDF中
            if page_num not in pages_to_remove:
                page = reader.getPage(page_num)
                writer.addPage(page)

        # 将输出写入新的PDF文件中
        with open(output, 'wb') as out_pdf:
            writer.write(out_pdf)

        print("output:", output)
    return output
